import GameUtil from "./GameUtil";
import { ICellData, ITempData } from "./IMessage";
import SceneGame, { EFlyType, EItemType } from "./SceneGame";

const { ccclass, property } = cc._decorator;

const MAX_WIDTH: number = 65;
const MAX_HEIGHT: number = 110;

@ccclass
export default class ItemIcon extends cc.Component {

    @property({ type: cc.Sprite, tooltip: "道具icon" })
    private icon: cc.Sprite = null;

    @property({ type: cc.Label, tooltip: "索引" })
    private labIndex: cc.Label = null;

    private cellData: ICellData = null;
    private tempData: ITempData = null;
    private index: number = 0;
    private itemId: number = -1;

    /**
     * 设置cell数据
     * @param data 
     * @param index
     */
    public setItemData(data: ICellData, index: number) {
        this.cellData = data;
        this.index = index;
        this.itemId = this.cellData.mids[data.curDeep + index];

        const color = GameUtil.instance.getColorByState(!(index > 0));
        this.icon.node.color = new cc.Color().fromHEX(color);
        GameUtil.instance.setItemIcon(EItemType.Item, this.itemId, this.icon, MAX_WIDTH, MAX_HEIGHT);

        if (GameUtil.isTest) {
            this.labIndex.string = `${this.itemId}`;
        }
    }

    /**
     * 设置暂存物品数据
     * @param data 
     * @param index 暂存区域:-1
     */
    public setTempData(data: ITempData, index: number) {
        this.tempData = data;
        this.index = index;
        this.itemId = data.itemId;
        // 暂存区移除按钮组件，否则会挡住人物解锁
        const comp = this.icon.node.getComponent(cc.Button);
        if (comp) {
            this.icon.node.removeComponent(cc.Button);
        }

        GameUtil.instance.setItemIcon(EItemType.Temp, this.itemId, this.icon, MAX_WIDTH, MAX_HEIGHT);

        if (GameUtil.isTest) {
            this.labIndex.string = `${this.itemId}`;
        }
    }

    // 测试
    private isTest: boolean = false;
    public setTestData(index: number, isTest: boolean) {
        this.isTest = isTest;
        GameUtil.instance.setItemIcon(EItemType.Test, index, this.icon, MAX_WIDTH, MAX_HEIGHT);
    }

    public shakeTip(id: number) {
        if (this.itemId === id && this.index != -1) {
            this.node.stopAllActions();
            cc.tween(this.node).sequence(
                cc.scaleTo(0.1, 1.2, 1.2).easing(cc.easeSineOut()),
                cc.scaleTo(0.1, 1, 1).easing(cc.easeSineOut()),
            ).start();
        }
    }

    private onBtnClicked(event: cc.Event, data: cc.Event.EventCustom) {
        if (this.isTest) {
            return;
        }

        if (this.index > 0 || this.index == -1 || !this.node.active) {
            return;
        }

        SceneGame.instance.flyItemIcon(null, this.node, this.itemId);
        this.cellData.mids[this.cellData.curDeep + this.index] = -1;
        this.cellData.curDeep++;
        SceneGame.instance.refreshGroup(this.cellData.gid, this.cellData.col, true);
    }
}